package com.app.micaihu.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.infor.AttentionStautsBean;
import com.app.micaihu.bean.infor.BlacklistBean;
import com.app.micaihu.bean.interactive.IDefriend;
import com.app.micaihu.bean.speak.IAttUser;
import com.app.micaihu.bean.speak.ICommentEntity;
import com.app.micaihu.bean.speak.ILaud;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.view.AttentionView;
import com.app.micaihu.custom.view.GoodView.GoodView;
import com.app.micaihu.custom.view.dialog.ReportDialog;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HandleListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.listener.LaudListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.view.user.userinfo.DefriendView;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.blankj.utilcode.util.ActivityUtils;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Guo on 2016/12/19.
 * <p>
 * 拉黑 点赞 关注 举报 操作存储在交互的 工具类
 */

public class InteractiveUtils {
    private static InteractiveUtils mInteractiveUtils;

    private GoodView mGoodView;

    private Context context;//当前的context
    private Context reportContext;
    private CustomPopWindow customPopWindow;//弹出的popwindow
    private ReportDialog reportDialog;//举报的dialog

    /*************
     * 点赞
     ***************/
    private File file;
    private RandomAccessFile ra;
    private static ArrayList<Long> memoryLaudList;
    private static ArrayList<String> memoryDefriendList;
    private boolean lauded;//是否进行存储
    private boolean isRequesting;//是否正在进行网络请求


    private InteractiveUtils() {
    }

    public static InteractiveUtils getInstance() {
        if (mInteractiveUtils == null) {
            mInteractiveUtils = new InteractiveUtils();
        }
        return mInteractiveUtils;
    }

    /**
     * 点赞动作
     *
     * @param view
     * @param laudListener
     */
    public void laud(@NonNull final ViewGroup view, final LaudListener laudListener) {
        if (view.getTag() == null || isRequesting) return;
        if (Boolean.valueOf(view.getTag().toString())) {
            ToastUtils.makeText(view.getContext().getResources().getString(R.string.common_already_zan_normal));
            return;
        }
        if (view.getTag() instanceof ILaud) {
            final ILaud laudEntity = (ILaud) view.getTag();
            if (laudListener != null) {
                laudListener.startCommit(laudEntity);
            }
            //请求点赞网络操作
            ParamMap parmsMap = new ParamMap();
            if (UserInforManager.getInstance().isLogin()) {
                parmsMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
            } else {
                parmsMap.putEncode("uid", "0");
            }
            parmsMap.putEncode("type", laudEntity.getILaudType());
            parmsMap.putEncode("articleId", laudEntity.getNewsId());
            parmsMap.putEncode("toUid", laudEntity.getIToUid());
            parmsMap.putEncode("commentId", laudEntity.getICommentId());
            parmsMap.putEncode("operateType", laudEntity.getILaudOperateType());
            parmsMap.putEncode("parentCmtId", laudEntity.getIParentCmtId());
            HttpUtils.ParmsMapMD5(parmsMap);

            HttpListener<DataBean> httpListener = new HttpListener<DataBean>() {
                @Override
                public void onStart() {
                    super.onStart();
                    isRequesting = true;
                }

                @Override
                public void onError(VolleyError error) {
                    if (view != null) {
                        view.setTag(laudEntity);
                    }
                    isRequesting = false;
                }

                @Override
                public void onSuccess(DataBean response) {
                    if (view != null && view.getChildCount() > 0 && view.getChildAt(0) != null
                            && view.getChildAt(0) instanceof TextView) {
                        if (response.noError()) {
                            View child = view.getChildAt(0);
                            TextView tv = (TextView) child;
                            child.setEnabled(false);
                            String zanNum = (StringUtils.toInt(laudEntity.getILaudNum(), 0) + 1) + "";
                            tv.setText(zanNum);
                            laudEntity.setILaudNum(zanNum);
                            //防止mGoodView 不能新建 导致popwindow不能弹出
                            if (mGoodView == null || context != view.getContext()) {
                                mGoodView = new GoodView(view.getContext());
                            }
                            context = child.getContext();
                            mGoodView.setTextInfo("+1", Color.parseColor("#e55d5d"), 12);
                            mGoodView.show(child);
                            view.setTag(true);

                            insertLaudIdToMemory(laudEntity);
                            if (laudListener != null) {
                                laudListener.finish(laudEntity);
                            }
                            lauded = true;
                        } else {
                            view.setTag(laudEntity);
                            ToastUtils.makeText(response.getNnderstoodMsg());
                        }
                    } else {
                        ToastUtils.makeText(response.getNnderstoodMsg());
                    }
                    isRequesting = false;
                }
            };
            //请求网络
            HttpUtils.addPostRequest(URIContant.NEWS_ZAN, new TypeToken<DataBean>() {
            }.getType(), null, parmsMap, httpListener);
        }
    }


    /**
     * 弹出popwindow 的操作
     *
     * @param view
     */
    public void showCommentPop(View view, View.OnClickListener onClickListener) {

        if (view.getTag(R.id.tag_first) instanceof ICommentEntity && view.getTag(R.id.tag_first) != null) {
            ICommentEntity commentEntity = (ICommentEntity) view.getTag(R.id.tag_first);

            if (customPopWindow == null || context != view.getContext()) {
                View contentView = LayoutInflater.from(view.getContext()).inflate(R.layout.popwin_comment_menu, null);

                customPopWindow = new CustomPopWindow.PopupWindowBuilder(view.getContext())
                        .setView(contentView)
                        .setFocusable(true)
                        .setOutsideTouchable(true)
                        .create();
            }
            this.context = view.getContext();

            View reply = customPopWindow.getView().findViewById(R.id.reply);
            View jubao = customPopWindow.getView().findViewById(R.id.jubao);
            View fuzhi = customPopWindow.getView().findViewById(R.id.fuzhi);
            View deleteView = customPopWindow.getView().findViewById(R.id.delete);
            View deleteLineView = customPopWindow.getView().findViewById(R.id.delete_line);
            View upView = customPopWindow.getView().findViewById(R.id.jiantou_up);
            View downView = customPopWindow.getView().findViewById(R.id.jiantou_down);
            reply.setOnClickListener(onClickListener);
            jubao.setOnClickListener(onClickListener);
            fuzhi.setOnClickListener(onClickListener);
            deleteView.setOnClickListener(onClickListener);


            int menuViewWidth = ViewSizeUtils.getViewW(customPopWindow.getView());
            int menuViewHeight = ViewSizeUtils.getViewH(customPopWindow.getView());

            int[] locations = new int[2];
            view.getLocationOnScreen(locations);
            int x = (ViewSizeUtils.getWidthPixels() - menuViewWidth) / 2;
            int y = 0;

            if (locations[1] <= ViewSizeUtils.getHeightPixels() / 3) {

                y = -menuViewHeight / 2;
                upView.setVisibility(View.VISIBLE);
                downView.setVisibility(View.GONE);
            } else {
                y = -(view.getHeight() + menuViewHeight / 2) + ViewSizeUtils.getViewH(upView);
                upView.setVisibility(View.GONE);
                downView.setVisibility(View.VISIBLE);
            }

            if (UserInforManager.getInstance().isLogin() &&
                    TextUtils.equals(UserInforManager.getInstance().getUserInfor().getUid(), commentEntity.getIToUid())
                    && deleteView != null) {
                //如果当前评论的作者就是用户本人则显示删除按钮
                deleteView.setVisibility(View.VISIBLE);
                deleteLineView.setVisibility(View.VISIBLE);
            } else if (deleteView != null) {
                deleteView.setVisibility(View.GONE);
                deleteLineView.setVisibility(View.GONE);
            }
            try {
                if (!((Activity) view.getContext()).isFinishing()) {
                    customPopWindow.showAsDropDown(view, x, y);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 关闭MenuPop
     */
    public void dimissCommentPop() {
        try {
            if (customPopWindow != null) {
                customPopWindow.dissmiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 复制
     */
    public void copy(ICommentEntity iCommentEntity) {
        if (iCommentEntity != null) {
            String content = iCommentEntity.getIContent();
            if (TextUtils.isEmpty(content) || context == null) {
                ToastUtils.makeText(AppApplication.getInstance().getString(R.string.common_copy_fail));
                return;
            }
            // 得到剪贴板管理器
            ClipboardManager cmb = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(content.trim());
            ToastUtils.makeText(AppApplication.getInstance().getString(R.string.common_copy_complete));
        }
    }

    /**
     * 展示举报的dialog
     * <p>
     * 在评论 或者帖子的评论中用
     */
    public void report(@NonNull View view, ICommentEntity iCommentEntity, boolean isComment) {
        if (iCommentEntity == null) {
            ToastUtils.makeText(AppApplication.getInstance().getString(R.string.common_report_fail));
            return;
        }
        final String id = iCommentEntity.getICommentId();
        String sql = "select * from " + NewsDBSqlHelper.COMMENT_REPORT + "where _id=" + id;
        boolean isReport = NewsDBUtil.getInstance().hasDataBySql(sql);
        if (isReport) {
            ToastUtils.makeText(AppApplication.getInstance().getString(R.string.common_report_already));
            return;
        } else {
            if (reportDialog == null || this.reportContext != view.getContext()) {
                if (view.getContext() instanceof Activity) {
                    reportDialog = new ReportDialog((Activity) view.getContext());
                } else {
                    reportDialog = new ReportDialog(ActivityUtils.getTopActivity());
                }
            }
            this.reportContext = view.getContext();
            String comid = null;
            if (iCommentEntity != null) {
                comid = iCommentEntity.getICommentId();
            }

            String reportTypeStatistics = "";
            String reportType = "";

            String iType = iCommentEntity.getIType();

            if (TextUtils.equals(iType, TypeConstant.COMMENT_PARENT)) {//类型是一级评论
                if (isComment) {//如果是评论
                    reportTypeStatistics = TypeConstant.PAGE_COMMENT;
                    reportType = TypeConstant.JUBAO_COMMENT_PARENT;
                } else {
                    reportTypeStatistics = TypeConstant.PAGE_POST;
                    reportType = TypeConstant.JUBAO_POST;
                }

            } else if (TextUtils.equals(iType, TypeConstant.COMMENT_ONE) || TextUtils.equals(iType, TypeConstant.COMMENT_TWO)) {
                if (isComment) {//如果是评论
                    reportTypeStatistics = TypeConstant.PAGE_COMMENT_CHILD;
                    reportType = TypeConstant.JUBAO_COMMENT_CHILD;
                } else {
                    reportTypeStatistics = TypeConstant.PAGE_POST_COMMENT_CHILD;
                    reportType = TypeConstant.JUBAO_POST_CHILD;
                }
            }

            reportDialog.show(comid, reportTypeStatistics, reportType);
        }
    }


    /**
     * 关注用户/作者
     */
    public void followUserOperat(final AttentionView view, final HandleListener handleListener) {
        this.context = view.getContext();

        if (view.getTag() != null && view.getTag() instanceof IAttUser) {

            Map<String, String> params = new HashMap<>();
            if (UserInforManager.getInstance().isLogin()) {
                params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
            } else {
                params.put("uid", "0");
            }
            params.put("toUid", ((IAttUser) view.getTag()).getIToUid());
            switch (((IAttUser) view.getTag()).getIAttType()) {
                case TypeConstant.ATTENTION_NO:
                    params.put("type", "1");
                    break;
                case TypeConstant.ATTENTION_YES:
                case TypeConstant.ATTENTION_ALL:
                    params.put("type", "2");
                    break;
                default:
                    params.put("type", "1");
                    break;

            }

            HttpListener<DataBean<AttentionStautsBean>> attentionListener = new HttpListener<DataBean<AttentionStautsBean>>() {
                @Override
                public void onStart() {
                    super.onStart();
                    if (handleListener != null) {
                        handleListener.handleStart(null);
                    }
                }

                @Override
                public void onError(VolleyError error) {
                    if (handleListener != null) {
                        handleListener.handleFail(null);
                    }
                    if (context != null) {
                        ToastUtils.makeText(context.getResources().getString(R.string.neterror));
                    }
                }

                @Override
                public void onSuccess(DataBean<AttentionStautsBean> response) {
                    if (response.noError() && response.getData() != null) {


                        ((IAttUser) view.getTag()).setIAttType(response.getData().getStatus());
//                        view.flushStatus(response.getData().getStatus());
                        if (handleListener != null) {
                            ArrayList<Object> list = new ArrayList<>();
                            list.add(response.getData().getStatus());
                            handleListener.handleSuccess(list);
                        }
                    } else {
                        if (handleListener != null) {
                            handleListener.handleFail(null);
                        }
                        ToastUtils.makeText(response.getNnderstoodMsg());
                    }
                }
            };

            HttpUtils.addPostRequest(URIContant.ATTENTION_OR_NO, new TypeToken<DataBean<AttentionStautsBean>>() {
            }.getType(), "", params, attentionListener);


        }


    }


    /**
     * 拉黑名单
     *
     * @param activity
     * @param iDefriend
     * @param view
     */
    public void defriend(Context activity, final IDefriend iDefriend, final DefriendView view) {
        this.context = activity;
        if (!UserInforManager.getInstance().isLogin()) return;

        final ParamMap param = new ParamMap();
        param.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        param.putEncode("toUid", iDefriend.getIToUid());
        param.putEncode("type", iDefriend.getIDefriendType());

        HttpUtils.ParmsMapMD5(param);

        final HttpListener<DataBean<String>> deFriendsListener = new HttpListener<DataBean<String>>() {
            @Override
            public void onStart() {
                super.onStart();
                if (context != null) {
                    DialogUtils.getInstance().showProgressDialog((Activity) context, AppApplication.getInstance().getResources().getString(R.string.homepage_attention_start));

                }
            }

            @Override
            public void onError(VolleyError error) {
                DialogUtils.getInstance().dismissProgressDialog();
                if (context != null) {
                    ToastUtils.makeText(context.getResources().getString(R.string.neterror));
                }
            }

            @Override
            public void onSuccess(DataBean<String> response) {
                DialogUtils.getInstance().dismissProgressDialog();

                if (TextUtils.equals(response.getCode(), "0")) {

                    if (iDefriend.getIInBlacklist()) {
                        ToastUtils.makeText("解除拉黑");
                        iDefriend.setInBlacklist("0");
                        insertDefriendtoMemory(iDefriend.getIToUid(), true);
                    } else {
                        ToastUtils.makeText("拉黑成功");
                        iDefriend.setInBlacklist("1");

                        insertDefriendtoMemory(iDefriend.getIToUid(), false);
                    }

                    if (view != null) {
                        view.flushStatus(iDefriend.getIInBlacklist());
                    }
                } else {
                    ToastUtils.makeText(response.getMsg());
                }
            }
        };

        HttpUtils.addPostRequest(URIContant.OPRATION_DEFRIEND, new TypeToken<DataBean<String>>() {
        }.getType(), null, param, deFriendsListener);

    }


    /**
     * 保存到本地赞
     */
    public synchronized void saveLaudList() {
        if (memoryLaudList == null) {
            memoryLaudList = new ArrayList<>();
        }
        if (memoryLaudList.size() <= 0) {
            return;
        }

        if (!lauded) {
            return;
        }

        if (UserInforManager.getInstance().isLogin()) {
            file = new File(AppApplication.getInstance().getFilesDir().getAbsolutePath(), UserInforManager.getInstance().getUserInfor().getUid() + "_laud.txt");
        } else {
            file = new File(AppApplication.getInstance().getFilesDir().getAbsolutePath(), "_laud.txt");
        }

        try {
            ra = new RandomAccessFile(file, "rw");
            ra.seek(0);
            for (Long aLong : memoryLaudList) {
                ra.writeLong(aLong);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lauded = false;
            if (ra != null) {
                try {
                    ra.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        LogUtils.e("gzq", "save_laud");
    }


    /**
     * 读取本地文件中 的zan 集合,返回long泛型的list
     *
     * @return
     */
    public synchronized ArrayList<Long> readLaudFromLocal() {
        if (memoryLaudList == null) {
            memoryLaudList = new ArrayList<>();
        }
        memoryLaudList.clear();
        if (UserInforManager.getInstance().isLogin()) {
            file = new File(AppApplication.getInstance().getFilesDir().getAbsolutePath(), UserInforManager.getInstance().getUserInfor().getUid() + "_laud.txt");
        } else {
            file = new File(AppApplication.getInstance().getFilesDir().getAbsolutePath(), "_laud.txt");
        }
//        LogUtils.e("gzq", "read_file.path = " + file.getAbsolutePath());
        try {
            ra = new RandomAccessFile(file, "rw");
            if (ra.length() <= 0) {
                return memoryLaudList;
            }
            ra.seek(0);
            for (int i = 0; i < ra.length() / 8; i++) {
                memoryLaudList.add(ra.readLong());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ra != null) {
                try {
                    ra.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return memoryLaudList;

    }


    /**
     * 将点赞 插入到内存中
     *
     * @param laudEntity
     */
    private void insertLaudIdToMemory(ILaud laudEntity) {
        if (laudEntity == null) return;
        if (memoryLaudList == null) {
            memoryLaudList = new ArrayList<>();
        }
        while (memoryLaudList.size() > 1000) {
            memoryLaudList.remove(0);
        }
        Long laudId = 0L;
        if (TextUtils.equals(laudEntity.getILaudType(), "0")) {//对资讯
            laudId = StringUtils.toLong(laudEntity.getNewsId(), 0L);
        } else {//普通点赞
            laudId = StringUtils.toLong(laudEntity.getICommentId(), 0L);
        }
        if (TextUtils.equals(TypeConstant.ZAN_DISLIKE, laudEntity.getILaudOperateType())) {
            laudId = -laudId;
        }
        if (!memoryLaudList.contains(laudId)) {
            memoryLaudList.add(laudId);
        }
    }
    /**
     * 获取当前内存中的赞list
     *
     * @return
     */
    public ArrayList<Long> getCurrentLaudList() {
        if (memoryLaudList == null) {
            memoryLaudList = readLaudFromLocal();
            getCurrentLaudList();
        }
        return memoryLaudList;

    }

    /**
     * 判断当前用户 是否点赞过
     *
     * @param laudId
     * @return
     */
    public boolean theLaudIsContains(String laudId, boolean like) {

        if (TextUtils.isEmpty(laudId)) {
            return false;
        }
        if (memoryLaudList == null) {
            memoryLaudList = readLaudFromLocal();
        }
        if (memoryLaudList != null && memoryLaudList.isEmpty()) {
            return false;
        }
        if (memoryLaudList != null && like && memoryLaudList.contains(StringUtils.toLong(laudId, 0L))) {
            return true;
        }

        if (memoryLaudList != null && !like && memoryLaudList.contains(-StringUtils.toLong(laudId, 0L))) {
            return true;
        }
        return false;
    }


    /******************************************************************/

    /**
     * 获取全部的 黑名单
     */
    public void getAllBlackList() {
        //如果没登录字节返回一个空的
        if (!UserInforManager.getInstance().isLogin()) {
            memoryDefriendList = new ArrayList<>();
            return;
        }
        ParamMap paramMap = new ParamMap();
        paramMap.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        paramMap.put("page", "1");
        paramMap.put("getAll", "1");//是否拉取全部 1是 0否
        HttpUtils.ParmsMapMD5(paramMap);

        HttpListener<DataBean<List<BlacklistBean>>> blackListListener = new HttpListener<DataBean<List<BlacklistBean>>>() {

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(DataBean<List<BlacklistBean>> response) {

                if (response.noError()) {
                    List<BlacklistBean> blacklists = response.getData();
                    if (blacklists != null) {
                        if (memoryDefriendList == null) {
                            memoryDefriendList = new ArrayList<>();
                        }
                        if (!blacklists.isEmpty()) {
                            memoryDefriendList.clear();
                            for (BlacklistBean blackItem : blacklists) {
                                memoryDefriendList.add(blackItem.getIToUid());
                            }
                        }
                    }
                }
            }
        };


        HttpUtils.addPostRequest(URIContant.BLACKLIST_LIST, new TypeToken<DataBean<List<BlacklistBean>>>() {
        }.getType(), "", paramMap, blackListListener);

    }


    /**
     * 保存到内存中
     *
     * @param defriendUid
     * @param isRemove
     */
    public void insertDefriendtoMemory(String defriendUid, boolean isRemove) {
        if (TextUtils.isEmpty(defriendUid)) return;

        if (memoryDefriendList == null) {
            memoryDefriendList = new ArrayList<>();
        }
        if (isRemove) {
            if (memoryDefriendList.contains(defriendUid)) {
                memoryDefriendList.remove(defriendUid);
            }
        } else {
            if (!memoryDefriendList.contains(defriendUid)) {
                memoryDefriendList.add(defriendUid);
            }
        }


    }

    /**
     * 判断是否是包含在黑名单里
     *
     * @param defriendUid
     * @return
     */
    public boolean theDefriendIsContains(String defriendUid) {
        if (TextUtils.isEmpty(defriendUid)) {
            return false;
        }
        if (memoryDefriendList == null) {
            getAllBlackList();
        }

        if (memoryDefriendList == null || memoryDefriendList.isEmpty()) {
            return false;
        }
        if (memoryDefriendList != null && memoryDefriendList.contains(defriendUid)) {
            return true;
        }
        return false;
    }


}
